<template>
  <div class="order-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="订单号">
        <el-input v-model="queryForm.keyword" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <div class="table-container">
      <el-table :data="orderList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="serialNumber" label="订单号" width="180" />
        <el-table-column prop="loginName" label="用户名" width="120" v-if="userType === 1" />
        <el-table-column prop="userAddress" label="收货地址" width="200" />
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="cost" label="订单金额" width="100" />
        <el-table-column label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="handlePay(scope.row)" 
                :disabled="scope.row.status !== 0"
                v-if="userType === 0"
              >
                支付
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleCancel(scope.row)" 
                :disabled="scope.row.status !== 0"
                v-if="userType === 0"
              >
                取消
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="detailVisible" width="60%">
      <div v-if="currentOrder">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentOrder.serialNumber }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ currentOrder.userAddress }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.cost }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <h3 style="margin-top: 20px;">订单商品</h3>
        <el-table :data="orderDetails" border style="width: 100%">
          <el-table-column prop="productId" label="商品ID" width="100" />
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="cost" label="小计" width="100" />
        </el-table>
      </div>
      <div v-else>
        加载中...
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, getOrderDetails, cancelOrder, payOrder } from '@/api/orderApi'

export default {
  name: 'OrderManagement',
  props: {
    userType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      // 查询表单
      queryForm: {
        keyword: ''
      },
      // 订单列表数据
      orderList: [],
      // 订单详情
      orderDetails: [],
      // 当前查看的订单
      currentOrder: null,
      // 分页数据
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 对话框状态
      detailVisible: false,
      // 加载状态
      loading: false
    }
  },
  methods: {
    // 查询订单
    handleQuery() {
      this.pagination.current = 1
      this.fetchOrderList()
    },
    // 重置查询
    resetQuery() {
      this.queryForm.keyword = ''
      this.handleQuery()
    },
    // 获取订单列表
    async fetchOrderList() {
      this.loading = true
      try {
        const params = {
          keyword: this.queryForm.keyword,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size
        }
        console.log('请求参数:', params)
        const res = await getOrderList(params)
        console.log('订单查询响应:', res)
        if (res.data) {
          this.orderList = res.data
          this.pagination.total = res.total
        } else {
          this.orderList = []
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'))
        this.orderList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    // 查看订单详情
    async handleView(row) {
      this.currentOrder = row
      this.detailVisible = true
      
      // 获取订单详情
      try {
        const res = await getOrderDetails(row.id)
        if (res) {
          this.orderDetails = res
        } else {
          this.orderDetails = []
        }
      } catch (error) {
        this.$message.error('获取订单详情失败')
        console.error('获取订单详情错误:', error)
        this.orderDetails = []
      }
    },
    // 支付订单
    async handlePay(row) {
      try {
        await this.$confirm(`确定要支付订单《${row.serialNumber}》吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true
        const response = await payOrder(row.serialNumber)
        // 创建一个临时的div元素来解析返回的HTML
        const parser = new DOMParser()
        const doc = parser.parseFromString(response, 'text/html')
        const form = doc.querySelector('form')
        
        if (form) {
          // 将表单添加到页面并自动提交
          document.body.appendChild(form)
          form.submit()
        } else {
          // 如果没有表单，可能是其他响应，显示成功消息并刷新列表
          this.$message.success('支付成功')
          this.fetchOrderList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('支付失败')
        }
      } finally {
        this.loading = false
      }
    },
    // 取消订单
    async handleCancel(row) {
      try {
        await this.$confirm(`确定要取消订单《${row.serialNumber}》吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.loading = true
        await cancelOrder(row.serialNumber)
        this.$message.success('取消成功')
        this.fetchOrderList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消失败')
        }
      } finally {
        this.loading = false
      }
    },
    // 处理分页大小改变
    handleSizeChange(size) {
      this.pagination.size = size
      this.fetchOrderList()
    },
    // 处理分页页码改变
    handleCurrentChange(current) {
      this.pagination.current = current
      this.fetchOrderList()
    },
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
    },
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '已完成',
        2: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    // 获取订单状态标签类型
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      }
      return typeMap[status] || 'info'
    }
  },
  // 创建完毕
  mounted() {
    this.fetchOrderList()
  }
}
</script>

<style scoped>
.order-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.table-container {
  margin: 0 !important;
}

/* 彻底解决el-table样式被全局样式覆盖的问题 */
.table-container :deep(.el-table) {
  margin: 0 !important;
  width: 100% !important;
}

.table-container :deep(.el-table__header-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__header) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(.el-table__body-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__body) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(table) {
  margin: 0 !important;
  border-collapse: separate !important;
  table-layout: fixed !important;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>